<script setup>
import { useFormConfigHook } from '@/hooks/usePlusConfigHook.js'
import { dataScope, deptTreeSelect, getRole } from '@/api/system/role.js'
const { proxy } = getCurrentInstance();
const gVisible = ref(false)
const deptOptions= ref([])
const emit = defineEmits('refreshList')

const gFormData = ref({
  roleId: null,
  roleName: null,
  roleKey: null,
  dataScope: null,
})


/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: '1', label: '全部数据权限' },
  { value: '2', label: '自定数据权限' },
  { value: '3', label: '本部门数据权限' },
  { value: '4', label: '本部门及以下数据权限' },
  { value: '5', label: '仅本人数据权限' }
])

const columns = [
  {
    label: '角色名称',
    prop: 'roleName',
    fieldProps:{
      disabled: true
    }
  },
  {
    label: '权限字符',
    prop: 'roleKey',
    fieldProps:{
      disabled: true
    }
  },
  {
    label: '权限范围',
    prop: 'dataScope',
    valueType:'select',
    options:dataScopeOptions,
    fieldProps: {
      clearable:false,
      onChange:val=>{
       if(val !== '2') deptRef.value.setCheckedKeys([])
      }
    }
  },
  {
    label: '权限范围',
    prop: 'deptScope',
    hideInForm:computed(()=> gFormData.value.dataScope !== '2')
  },
]


const deptRef = ref(null)
/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) {
  return deptTreeSelect(roleId).then((response) => {
    deptOptions.value = response.data.depts
    return response.data
  })
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  deptRef.value.setCheckedNodes(value ? deptOptions.value : [])
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  gFormData.value.deptCheckStrictly = !!value
}
/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  let treeList = deptOptions.value
  for (let i = 0; i < treeList.length; i++) {
    deptRef.value.store.nodesMap[treeList[i].id].expanded = value
  }
}
/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value.getCheckedKeys()
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}
const deptExpand = ref(true)
const deptNodeAll = ref(false)
const gFormRule = ref([])
const gTitle = ref('分配数据权限')
const gConfirmLoading = ref(false)
const gClose = ()=>{
  deptExpand.value = true
  deptNodeAll.value = false
  gFormData.value = {}
}
const gSubmitForm = ()=>{
  if(!gFormData.value.roleId) return false;
  if( gFormData.value.dataScope === '2'){
    gFormData.value.deptIds = getDeptAllCheckedKeys()
  }else{
    gFormData.value.deptIds = []
  }
  dataScope(gFormData.value).then(() => {
    proxy.$modal.msgSuccess('修改成功')
    gVisible.value = false
    emit('refreshList')
  })
}

const gOpen =  (row)=>{
  const deptTreeSelect = getDeptTree(row.roleId)
  getRole(row.roleId).then(async ({ data }) => {
    gFormData.value = data
    gVisible.value = true
    await nextTick()
    deptTreeSelect.then((res) => {
      nextTick(() => {
        console.log('res.checkedKeys',res)
        if (deptRef.value)  {
          deptRef.value.setCheckedKeys(res.checkedKeys)
        }
      })
    })
  })
}

const { gDialogConfig,  gFormConfig} = useFormConfigHook({
  gFormRule,gConfirmLoading,gClose,gSubmitForm,gTitle
},{
  dialogConfig:{},
  formConfig:{
    labelWidth: 120,
  }
});

defineExpose({
  gOpen
})

</script>

<template>
  <PlusDialog v-model="gVisible"  v-bind="gDialogConfig">
    <PlusForm ref="gFormInstance" v-model="gFormData" :columns="columns" v-bind="gFormConfig">
      <template #plus-field-deptScope>
        <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
        <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
        <el-checkbox v-model="gFormData.deptCheckStrictly" @change="handleCheckedTreeConnect">父子联动</el-checkbox>
        <el-tree
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="deptRef"
          node-key="id"
          :check-strictly="!gFormData.deptCheckStrictly"
          empty-text="加载中，请稍候"
          :props="{ label: 'label', children: 'children' }"
        ></el-tree>
      </template>
    </PlusForm>
  </PlusDialog>
</template>
<style scoped lang="scss">

</style>
